package controllers;

import java.util.Date;

import models.User;
import play.db.ebean.Model.Finder;
import play.mvc.Result;
import play.mvc.Http.Context;
import play.mvc.Http.Cookie;
import play.mvc.Security.Authenticator;

/*
 * Admin authenticator
 * Author: Talasbek Assem
 */

public class SecuredAdmin extends Authenticator {

	@Override
	public String getUsername(Context ctx) {
		if(ctx.session().get("uname") == null || User.find.where().eq("username", ctx.session().get("uname")).findRowCount() == 0)
			return null;
		String prevTick = ctx.session().get("userTime");
		if(prevTick != null && !prevTick.equals(""))
		{
			long prevT = Long.valueOf(prevTick);
			long currentT = new Date().getTime();
			long timeOut = 30 * 1000 * 60;
			if((currentT - prevT) > timeOut)
			{
				ctx.session().clear();
				return null;
			}
		}
		if(!"1".equals(ctx.session().get("role")))
			return null;
		String tickString = Long.toString(new Date().getTime());
		ctx.session().put("userTime", tickString);
		return ctx.session().get("uname");
	}
/*
	@Override
	public String getUsername(Context ctx) {
		Iterable<Cookie> it = ctx.response().cookies();
		String username = null;
		int i = 0;
		for(Cookie c : it)
		{
			System.out.println(c.name());
			if("uname".equals(c.name()))
			{
				System.out.println(true);
				username = c.value();
				i = User.find.where().eq("username", username).findRowCount();
			}
			if(i!=0 && "role".equals(c.name()))
			{
				System.out.println(true);
				if(!c.value().equals("1"))
				{
					i = 0;
					break;
				}
			}
		}
		System.out.println(true);
		return i==0?null:username;
	}
	*/
	@Override
	public Result onUnauthorized(Context ctx) {
		return redirect(routes.Application.index());
	}	
}